package com.zhiwei.gateway.service.impl;

import com.google.code.kaptcha.Producer;
import com.zhiwei.common.service.CacheService;
import com.zhiwei.common.util.ImageUtil;
import com.zhiwei.common.util.RandomCodeGenerator;
import com.zhiwei.gateway.service.CaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.awt.image.BufferedImage;

/**
 * function 默认验证码服务
 * author zhiwei.yang
 * time 2020-2-27-16:26
 */
@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Value("${spring.application.name}")
    private String appName;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private Producer producer;

    @Override
    public String getCaptcha() {
        return getCaptcha(null);
    }

    @Override
    public String getCaptcha(String serialNo) {
        String captcha = RandomCodeGenerator.generate();
        if(!StringUtils.isEmpty(serialNo)){
            this.saveCaptcha(serialNo, captcha); //保存验证码用于后续校验
        }else{
            this.saveCaptcha(captcha);
        }
        BufferedImage bufferedImage = producer.createImage(captcha);
        return ImageUtil.imageToBase64(bufferedImage);
    }

    @Override
    public void removeCaptcha(String serialNo) {
         cacheService.removeCacheObject(appName, serialNo);
    }

    @Override
    public boolean matches(String captcha) {
        return matches(null, captcha);
    }

    @Override
    public boolean matches(String serialNo, String captcha) {
        if(!StringUtils.isEmpty(serialNo)){
            String savedCaptcha = this.queryCaptchaByKey(serialNo);
            return captcha.equalsIgnoreCase(savedCaptcha);
        }
        return captcha.equalsIgnoreCase(this.queryCaptchaByKey(captcha));
    }

    @Override
    public void saveCaptcha(String captcha) {
        cacheService.putCacheObject(appName, captcha, null);
    }

    @Override
    public void saveCaptcha(String serialNo, String captcha) {
        cacheService.putCacheObject(appName, serialNo, captcha);
    }

    @Override
    public String queryCaptchaByKey(String key) {

        //缓存值不为空(类似HashMap)
        String cacheValue = (String)cacheService.getCacheObject(appName, key);
        if(!StringUtils.isEmpty(cacheValue)){
            return cacheValue;
        }

        //缓存值为空(类似HashSet)
        if(cacheService.isExistCacheKey(appName, key)){
            cacheService.removeCacheObject(appName, key);
            return key;
        }
        return null;
    }
}
